import xlwt
from openpyxl import load_workbook
import xlsxwriter
import configparser
from PIL import Image, ImageChops
import os


class AboutExcel():

    def __init__(self,filePath,savePath):
        '''

        :param filePath: the 8bit img path (about tablet labels img)
        :param savePath: the 32bit img path which you need to save
        '''

        self.filePath = filePath
        self.savePath = savePath

    def readConfig(self):
        self.cf = configparser.ConfigParser()
        self.cf.read("../setting/config.ini",encoding="utf-8-sig")  # 读取配置文件

    def getTabletImgName(self):
        '''

        :return:list of tablet img name
        '''
        self.cf = configparser.ConfigParser()
        self.cf.read("./setting/config.ini", encoding="utf-8-sig")  # 读取配置文件
        table_img_name = self.cf.get("M11_ROW_WIFI",'table_img_name')

        tablet_list = table_img_name.split("\n")

        return tablet_list

    def readFileName(self):
        '''
        获取平板图片文件夹下面的所有文件名字（平板获取到的时八位图，需要转换成32位图才能插入表格）
        :return: 返回文件夹下面所有文件的名字，是一个列表
        '''
        tablet_labels_name = os.listdir(self.filePath)
        # print(tablet_labels_name)
        return tablet_labels_name


    def getTabletImg(self):
        tabletImgPath = Image.open(self.filePath) #打开8位图
        print(tabletImgPath.mode,"%%%%%%%%%%8位的")
        uu = tabletImgPath.convert("RGBA") #修改八位图的模式为32位
        print(uu.mode,"修改了的8位的")
        uu.save(self.savePath) #保存修改好的32位图

        return tabletImgPath


    def getWordImgName(self):
        '''

        :return: 按照img的名称顺序返回wordimg的名称
        '''
        word_labels_name = os.listdir("./word_img/")

        #对获取到的word_img的名称进行排序
        # image1.png 以.分割 [image1][png],取[image1]的第六位往后作为关键字排序
        word_labels_name.sort(key=lambda x: int(x.split('.')[0][5:]))

        return word_labels_name



    def change_8bit_to_32bit(self):
        '''

        :return: the 8bit imgs and 32bit imgs path list
        '''

        #获取平板图片文件夹下面的所有文件名字（平板获取到的是8bit图，需要转换成32位图才能插入表格）

        # 返回文件夹下面所有文件的名字，是一个列表

        tablet_labels_name = os.listdir(self.filePath)
        print(tablet_labels_name)


        for i in tablet_labels_name:
            labels_img_path = self.filePath + i      #拼接8位图片路径
            lables_32bit_save_path = self.savePath + i   #拼接32位图片保存位置的路径（已原图片名字命名）
            tabletImgPath = Image.open(labels_img_path)     # 打开8位图
            # print(tabletImgPath.mode, "%%%%%%%%%%8位的模式%%%%%%%%")

            change_bit = tabletImgPath.convert("RGBA")  # 修改八位图的模式为32位
            print(change_bit.mode, "修改了的8位的位图模式为")
            change_bit.save(lables_32bit_save_path)  # 保存修改好的32位图

            # #修改图片尺寸
            # img_size = Image.open(lables_32bit_save_path)
            # (x, y) = img_size.size
            # x = int(x / 10)
            # y = int(y / 10)
            # change_size = img_size.resize((x, y), Image.ANTIALIAS)
            # change_size.save(lables_32bit_save_path)

    def creat_img_excel(self,result_path):
        self.tablet_img_name = self.getTabletImgName()
        # print(self.tablet_img_name) #打印图像名称
        excel_length = len(self.tablet_img_name)
        # self.tablet_img_file = self.savePath
        self.tablet_img_file = './tablet_img/'
        result_path = result_path + '/labels_img_compare_result.xlsx'
        workbook = xlsxwriter.Workbook(result_path)
        sheet = workbook.add_worksheet("tablet_img")

        excel_format = {'align': 'center','valign': 'vcenter','text_wrap':1 }
        cell_format = workbook.add_format(excel_format)  # 获取单元格属性

        # {'bold': True, 'font_size': 14, 'ali gn': 'center','valign': 'vcenter','border':1,
        # 'color':'red', 'bg_color':'blue'}

        sheet.set_column('A:A', 15,cell_format=cell_format)  # 设置A列宽度15
        sheet.set_column('B:B', 15,cell_format=cell_format)  # 设置B列宽度15
        # cell_format = workbook.add_format({'bold': True})
        for i in range(excel_length+1):
            sheet.set_row(i, 30,cell_format=cell_format)  # 设置第i行高度为30

        sheet.write(0,0,"word_img")  #给第一行第一列写标题
        sheet.write(0,1,"tabelt_img")  #给第一行第二列写标题
        sheet.write(0,2,"result") #给第一行第三列写标题，结果

        # 为第一列设置格式
        # options = {'x_scale': 1,'y_scale': 1,'x_offset': 15, 'y_offset': 8}
        # print("长度",excel_length)

        #实验步骤
        # tablet_img_path = self.tablet_img_file + self.tablet_img_name[0]
        # sheet.insert_image(1, 1, '../tablet_img/e_label_bis_01.png', options)

        for i in range(excel_length):

            tablet_img_path = self.tablet_img_file + self.tablet_img_name[i]
            # print(tablet_img_path)

            img_size = Image.open(tablet_img_path)
            (width, height) = img_size.size # 获取图片的宽高
            i = i+1 #空出第一行

            # #---------------------------------------------------------------------------
            # # 固定宽度为56 需要转换成float的原因是这个format出来的是str，表格需要数字
            # x_scale = float(format(60/width,'.2f'))
            # y_scale = float(format(60/width,'.2f'))
            # print(x_scale,img_size.size)
            # #待优化算法,x和y轴的间距需要根据比例再进行计算
            # options = {'x_scale': x_scale, 'y_scale': x_scale, 'x_offset': 15, 'y_offset': 4}
            # sheet.insert_image(i, 1, tablet_img_path, options)
            # # ---------------------------------------------------------------------------

            #插入平板的图片进入表格
            #（此处为tablet labels）把图片分类，插入进去表格
            if width > 1000:
                options = {'x_scale': 0.08, 'y_scale': 0.08, 'x_offset': 5, 'y_offset': 21}
                sheet.insert_image(i, 1, tablet_img_path, options) #写入第i行，第二列

            elif height < 200 and width < 800:
                options = {'x_scale': 0.09, 'y_scale': 0.09, 'x_offset': 20, 'y_offset': 21}
                sheet.insert_image(i, 1, tablet_img_path, options)

            else:
                # x_scale = format(120 / x, '.1f')
                # y_scale = format(120 / x, '.1f')
                options = {'x_scale': 0.08, 'y_scale': 0.08, 'x_offset': 30, 'y_offset': 4}
                sheet.insert_image(i,1,tablet_img_path,options)

        #插入word的图片进入表格
        wordImgFile = "./word_img/"
        wordImgName = self.getWordImgName() # word图片的一个列表

        for i in range(len(wordImgName)):
            wordImgpath = wordImgFile + wordImgName[i]
            img_size = Image.open(wordImgpath)
            (width, height) = img_size.size  # 获取图片的宽高
            i = i + 1  # 空出第一行
            if width > 1000:
                options = {'x_scale': 1, 'y_scale': 1, 'x_offset': 5, 'y_offset': 21}
                sheet.insert_image(i, 0, wordImgpath, options)  # 写入第i行，第一列

            elif height < 200 and width < 800:
                options = {'x_scale': 1, 'y_scale': 1, 'x_offset': 20, 'y_offset': 21}
                sheet.insert_image(i, 0, wordImgpath, options)

            else:
                # x_scale = format(120 / x, '.1f')
                # y_scale = format(120 / x, '.1f')
                options = {'x_scale': 1, 'y_scale': 1, 'x_offset': 25, 'y_offset': 6}
                sheet.insert_image(i, 0, wordImgpath, options)

        for i in range(excel_length):
            wordImgpath = wordImgFile + wordImgName[i]
            tablet_img_path = self.tablet_img_file + self.tablet_img_name[i]

            image_word = Image.open(wordImgpath).convert("RGBA") #把word图片置换为RGBA模式
            image_tablet = Image.open(tablet_img_path).convert("RGBA")  #把tablet图片置换为RGBA模式
            i= i + 1 #空出第一行,从第二行开始写内容
            try:
                diff = ImageChops.difference(image_word, image_tablet)
                if diff.getbbox() is None:
                    # 图片间没有任何不同则直接退出
                    sheet.write(i,2,"PASS") #在第三列,图片对比的结果写进去表格
                else:
                    sheet.write(i,2,"不一样") #在第三列,图片对比的结果写进去表格
            except:
                pass
        print("图片对比完成，结果已写入表格！")

            # except ValueError as e:
            #     print(e)



        workbook.close()


    def writeIMgIntoExcel(self):
        # file_name = self.creatExcel()
        file_name = './Excel_row_height.xls'
        print(file_name,"name")
        open_file = xlsxwriter.Workbook('./Excel_row_height.xls')
        print(open_file.sheetnames)
        sheet = open_file.get_worksheet_by_name('My sheet1')
        print(sheet,"###########33sheet")
        # sheet.insert_image('0',"0","./zipImg/RNZ.png")

# if __name__ == '__main__':
#
#     run = AboutExcel('../tablet_img/','../tablet_temp_img/')
#     # run.readFileName()
#     # run.change_8bit_to_32bit('../tablet_img/','../tablet_temp_img/')
#     # run.creat_img_excel()
#     # print(run.getTabletImgName())
#     run.creat_img_excel()
#     # run.writeIMgIntoExcel()